package com.chengjue.transaction.learn.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
 * 描述:
 *
 * @author Kipeng Huang
 * @create 2018-03-04 下午4:19
 */
public class LearnChannel {
	public static void main(String[] args) throws FileNotFoundException {
		write("/home/kipeng/LearnNIO", "first NIO programme by 黄鹏 2018/03/04");

		System.out.println(read("/home/kipeng/LearnNIO"));
	}

	static void write(String path, String content) {
		File file = new File(path);
		FileOutputStream outputStream = null;
		FileChannel channel = null;
		try {
			outputStream = new FileOutputStream(file, true);
			channel = outputStream.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			buffer.put(content.getBytes());
			//准备开始读取buffer
			buffer.flip();
			//写入数据
			channel.write(buffer);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (channel != null) {
				try {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}


	static String read(String name) {

		File file = new File(name);
		if (!file.exists()) {
			return "文件不存在";
		}
		FileInputStream fileInputStream = null;
		FileChannel fileChannel = null;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			fileInputStream = new FileInputStream(file);
			fileChannel = fileInputStream.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			byte[] bytes = new byte[1024];
			while (fileChannel.read(buffer) != -1) {
				buffer.flip();
				buffer.get(bytes, 0, buffer.limit());
				stringBuilder.append(new String(bytes, 0 ,buffer.limit()));
				buffer.clear();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (fileChannel != null) {
				try {
					fileChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return stringBuilder.toString();
	}
}
